package cn.keduox.service.impl;

import cn.keduox.dao.impl.*;
import cn.keduox.entity.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/31 0031.
 */
public class BookServiceImpl extends BaseServiceImpl {
    /**
     * 查询书籍所有类型
     */
    public List<FirstType> findAllType() {
        //创建相关数据实现类
        FirstTypeDaoImpl firstTypeDao = new FirstTypeDaoImpl();
        try {
            List<FirstType> firstTypeList = firstTypeDao.select(new FirstType(), false, false, new PageBean(), false, null);
            return firstTypeList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查找一级类型子类型
     */
    public List<SubType> findSubType(FirstType firstType) throws Exception {
        SubTypeDaoImpl subTypeDao = new SubTypeDaoImpl();
        String firstTypeId = firstType.getId();
        SubType subType = new SubType();
        subType.setFirstTypeId(firstTypeId);
        List<SubType> subTypeList = subTypeDao.select(subType, false, false, new PageBean(), false, null);
        return subTypeList;
    }

    /**
     * 查找二级类型
     */
    public List<SecondType> findSecondType(SubType subType) throws Exception {
        SecondTypeDaoImpl secondTypeDao = new SecondTypeDaoImpl();
        String subTypeId = subType.getId();
        SecondType secondType = new SecondType();
        secondType.setSubTypeId(subTypeId);
        List<SecondType> secondTypes = secondTypeDao.select(secondType, false, false, new PageBean(), false, null);
        return secondTypes;
    }

    /**
     * 通过一级类型查询书目
     */
    public PageBean findBookByFirstType(String firstTypeId) {
        List<Book> bookList = new ArrayList<>();
        //查询一级类子类
        FirstType firstType = new FirstType();
        firstType.setId(firstTypeId);
        FirstTypeDaoImpl firstTypeDao = new FirstTypeDaoImpl();
        try {
            List<FirstType> firstTypeList = firstTypeDao.select(firstType, false, false, new PageBean(), false, null);
            if (firstTypeList != null && firstTypeList.size() != 0) {
                firstType = firstTypeList.get(0);
                List<SubType> subTypeList = findSubType(firstType);
                //遍历集合
                if (subTypeList.size() != 0 && subTypeList.size() != 0) {
                    for (SubType subType : subTypeList) {
                        //一级子标题封装二级标题
                        subType.setFirstType(firstType);
                        List<SecondType> secondTypeList = subType.getSecondTypeList();
                        if (secondTypeList != null && secondTypeList.size() != 0) {
                            for (SecondType secondType : secondTypeList) {
                                //二级标题封装一级子标题
                                secondType.setSubType(subType);
                                List<Book> bookList1 = getBookBySecondType(secondType);
                                bookList.addAll(bookList1);
                            }
                        }
                    }
                }
            }
            PageBean<Book> pageBean=new PageBean<Book>();
            pageBean.setCurrentPage(1);
            pageBean.setCurrentCount(2);
            pageBean.setTotalCount(bookList.size());
            pageBean.setTotalPage((int) Math.ceil(1.0*bookList.size()/2));
            pageBean=pageBeanSetList(pageBean,bookList);
            return pageBean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询价位区间
     */
    public List<PriceSection> findAllPriceSection() {
        PriceSectionDaoImpl priceSectionDao = new PriceSectionDaoImpl();
        try {
            List<PriceSection> priceSectionList = priceSectionDao.select(new PriceSection(), false, false, new PageBean(), false, null);
            return priceSectionList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据地址读取txt文档的方法
     */
    public static String txt2String(String fileUrl) {
        File file = new File(fileUrl);
        StringBuffer result = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String s = null;
            while ((s = br.readLine()) != null) {
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 排序分组查询
     */
    public OrderBookResult orderFind(String[] conStr, PageBean pageBean) {
        //查询出所有图书，查询出需要的类型，进行过滤
        BookDaoImpl bookDao = new BookDaoImpl();
        FirstTypeDaoImpl firstTypeDao = new FirstTypeDaoImpl();
        SecondTypeDaoImpl secondTypeDao = new SecondTypeDaoImpl();
        SubTypeDaoImpl subTypeDao = new SubTypeDaoImpl();
        //用于过滤的二级书籍类型id
        List<SecondType> typeList = new ArrayList<>();
        try {
            //判断书籍类型,并查询这种书籍的bookversion
            String typeId = conStr[4];
            if (conStr[0].equals("1")) {
                //一级类
                FirstType firstType = new FirstType();
                firstType.setId(typeId);
                List<FirstType> firstTypeList = firstTypeDao.select(firstType, false, false, new PageBean(), false, null);
                firstType = firstTypeList.get(0);
                //取出其中的二级类id
                List<SubType> subTypeList = firstType.getSubTypeList();
                for (SubType subType : subTypeList) {
                    subType.setFirstType(firstType);
                    List<SecondType> secondTypeList = subType.getSecondTypeList();
                    for (SecondType secondType : secondTypeList) {
                        if (secondType != null) {
                            typeList.add(secondType);
                        }
                    }
                }
            } else if (conStr[0].equals("2")) {
                //一级类子类
                SubType subType=new SubType();
                subType.setId(typeId);
                List<SubType> subTypeList=subTypeDao.select(subType,false,false,new PageBean(),false,null);
                subType=subTypeList.get(0);
                FirstType firstType=new FirstType();
                firstType.setId(subType.getFirstTypeId());
                firstType=firstTypeDao.select(firstType,false,false,new PageBean(),false,null).get(0);
                subType.setFirstType(firstType);
                List<SecondType> secondTypeList = subType.getSecondTypeList();
                for (SecondType secondType : secondTypeList) {
                    secondType.setSubType(subType);
                    if (secondType != null) {
                        typeList.add(secondType);
                    }
                }
            } else if (conStr[0].equals("3")) {
                //二级类
                SecondType secondType=new SecondType();
                secondType.setId(typeId);
                List<SecondType> secondTypeList=secondTypeDao.select(secondType,false,false,new PageBean(),false,null);
                secondType=secondTypeList.get(0);
                secondType=secondTypeHaveFirst(secondType);
                typeList.add(secondType);
            }
            //过滤器准备完毕,开始查询所有书籍
            Book book = new Book();
            //封装条件
            /**
             * 用于控制的标志数据集合，
             * 第一位代表当前查询书籍的目录类,1为一级目录，2为一级目录子目录，3为三级目录
             * 第二位表示排序项目,取值为1到6,相应对应项见前端
             * 第三位表示升降序，1升2降0无效
             * 第四位表示书的售价区间，0无效，其他对应前端
             * 第五位表示书籍类型的id，这个id可能是一级，一级子类，也可能二级
             */
            //售书区间
            if(!(conStr[3].equals("0"))){
                book.setSectionId(conStr[3]);
            }
            //取出排序项
            String orderStr=null;
            switch (conStr[1]){
                case "1":
                    orderStr="id";
                    break;
                case "2":
                    orderStr="sales";
                    break;
                case "3":
                    orderStr="press_time";
                    break;
                case "4":
                    orderStr="market_price";
                    break;
                case "5":
                    orderStr="cost_price";
                    break;
                case "6":
                    orderStr="score";
                    break;
            }
            List<Book> bookList=new ArrayList<>();
            if(!conStr[2].equals("0")){
                bookList=bookDao.select(book,false,conStr[2].equals("1"),new PageBean(),false, orderStr);
            }else {
                bookList=bookDao.select(book,false,false,new PageBean(),false, null);
            }
            List<Book> resultBookList=new ArrayList<>();
            //过滤
            for(Book book1:bookList){
                for(SecondType secondType:typeList){
                    if(secondType.getId().equals(book1.getTypeId())){
                        //封装书本的内容详情
                        BookTxt bookTxt=book1.getBookTxt();
                        if (bookTxt.getContentUrl() != null && !bookTxt.getContentUrl().equals("")) {
                            bookTxt.setContent(txt2String(bookTxt.getContentUrl()));
                        }
                        //封装书本的类型
                        book1.setSecondType(secondType);
                        resultBookList.add(book1);
                    }
                }
            }
            pageBean.setTotalCount(resultBookList.size());
            pageBean.setTotalPage((int) Math.ceil(1.0*resultBookList.size()/pageBean.getCurrentCount()));
            pageBean=pageBeanSetList(pageBean,resultBookList);
            OrderBookResult bookResult=new OrderBookResult(pageBean,conStr);
            return bookResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 通过一级类型子类型查询书目
     */
    public PageBean<Book> findBookBysubType(String subTypeId) {
        List<Book> bookList = new ArrayList<>();
        //查询类型
        SubType subType = new SubType();
        subType.setId(subTypeId);
        SubTypeDaoImpl subTypeDao = new SubTypeDaoImpl();
        FirstTypeDaoImpl firstTypeDao = new FirstTypeDaoImpl();
        try {
            List<SubType> subTypeList = subTypeDao.select(subType, false, false, new PageBean(), false, null);
            if (subTypeList != null && subTypeList.size() != 0) {
                subType = subTypeList.get(0);
                //subType封装firstType
                FirstType firstType = new FirstType();
                firstType.setId(subType.getFirstTypeId());
                List<FirstType> firstTypes = firstTypeDao.select(firstType, false, false, new PageBean(), false, null);
                subType.setFirstType(firstTypes.get(0));
                //遍历
                List<SecondType> secondTypeList = subType.getSecondTypeList();
                if (secondTypeList.size() != 0 && secondTypeList != null) {
                    for (SecondType secondType : secondTypeList) {
                        secondType.setSubType(subType);
                        List<Book> bookList1 = getBookBySecondType(secondType);
                        bookList.addAll(bookList1);
                    }
                }
            }
            PageBean<Book> pageBean=new PageBean<Book>();
            pageBean.setCurrentPage(1);
            pageBean.setCurrentCount(2);
            pageBean.setTotalCount(bookList.size());
            pageBean.setTotalPage((int) Math.ceil(1.0*bookList.size()/2));
            pageBean=pageBeanSetList(pageBean,bookList);
            return pageBean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过二级类型查询书目
     */
    public PageBean findBookBySecondType(String secondTypeId) {
        List<Book> bookList = new ArrayList<>();
        //查询类型
        SecondTypeDaoImpl secondTypeDao = new SecondTypeDaoImpl();
        SecondType secondType = new SecondType();
        secondType.setId(secondTypeId);
        try {
            List<SecondType> secondTypeList = secondTypeDao.select(secondType, false, false, new PageBean(), false, null);
            if (secondTypeList != null && secondTypeList.size() != 0) {
                secondType = secondTypeList.get(0);
                //查询一级子标题
                secondType=secondTypeHaveFirst(secondType);
                bookList = getBookBySecondType(secondType);
            }
            PageBean<Book> pageBean=new PageBean<Book>();
            pageBean.setCurrentPage(1);
            pageBean.setCurrentCount(2);
            pageBean.setTotalCount(bookList.size());
            pageBean.setTotalPage((int) Math.ceil(1.0*bookList.size()/2));
            pageBean=pageBeanSetList(pageBean,bookList);
            return pageBean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 二级标题封装一级标题
     */
    private SecondType secondTypeHaveFirst(SecondType secondType) throws Exception {
        SubTypeDaoImpl subTypeDao=new SubTypeDaoImpl();
        FirstTypeDaoImpl firstTypeDao=new FirstTypeDaoImpl();
        SubType subType = new SubType();
        subType.setId(secondType.getSubTypeId());
        List<SubType> subTypeList = subTypeDao.select(subType, false, false, new PageBean(), false, null);
        subType = subTypeList.get(0);
        FirstType firstType = new FirstType();
        firstType.setId(subType.getFirstTypeId());
        List<FirstType> firstTypes = firstTypeDao.select(firstType, false, false, new PageBean(), false, null);
        subType.setFirstType(firstTypes.get(0));
        secondType.setSubType(subType);
        return secondType;
    }
    /**
     * 已知二级标题封装书籍
     */
    private List<Book> getBookBySecondType(SecondType secondType) {
        List<Book> bookList=secondType.getBookList();
        BookTxt bookTxt;
        if (bookList != null && bookList.size() != 0) {
            for (Book book : bookList) {
                book.setSecondType(secondType);
                //封装文档信息
                bookTxt = book.getBookTxt();
                if (bookTxt.getFeatureUrl() != null && !bookTxt.getFeatureUrl().equals("")) {
                    bookTxt.setFeature(txt2String(bookTxt.getFeatureUrl()));
                }
                if (bookTxt.getContentUrl() != null && !bookTxt.getContentUrl().equals("")) {
                    bookTxt.setContent(txt2String(bookTxt.getContentUrl()));
                }
                if (bookTxt.getCatalogUrl() != null && !bookTxt.getCatalogUrl().equals("")) {
                    bookTxt.setCatalog(txt2String(bookTxt.getCatalogUrl()));
                }
                if (bookTxt.getRelinfoUrl() != null && !bookTxt.getRelinfoUrl().equals("")) {
                    bookTxt.setRelinfo(txt2String(bookTxt.getRelinfoUrl()));
                }
                if (bookTxt.getAuthorinfoUrl() != null && !bookTxt.getAuthorinfoUrl().equals("")) {
                    bookTxt.setAuthorinfo(txt2String(bookTxt.getAuthorinfoUrl()));
                }
                book.setBookTxt(bookTxt);
                //详情无需封装，在查询的时候已经自动封装了
                //将书籍添加到结果集合中
            }
        }
        return bookList;
    }
    /**
     * 对pageBean设置集合
     */
    private PageBean<Book> pageBeanSetList(PageBean<Book> pageBean,List<Book> bookList) {

        if ((pageBean.getCurrentCount()*(pageBean.getCurrentPage()-1)+pageBean.getCurrentCount())<bookList.size()){
            List<Book> sonList=bookList.subList(pageBean.getCurrentCount()*(pageBean.getCurrentPage()-1),pageBean.getCurrentCount()+pageBean.getCurrentCount()*(pageBean.getCurrentPage()-1));
            pageBean.setList(sonList);
        }else {
            List<Book> sonList=bookList.subList(pageBean.getCurrentCount()*(pageBean.getCurrentPage()-1),bookList.size());
            pageBean.setList(sonList);
        }
        return pageBean;
    }

    /**
     *查询书籍的详情
     */
    public Book bookInfo(String bookId) {
        //查询
        Book book=new Book();
        BookDaoImpl bookDao=new BookDaoImpl();
        SecondTypeDaoImpl secondTypeDao=new SecondTypeDaoImpl();
        book.setId(bookId);
        try {
            book=bookDao.select(book,false,false,new PageBean(),false,null).get(0);
            //对bookTxt封装
            BookTxt bookTxt = book.getBookTxt();
            if (bookTxt.getFeatureUrl() != null && !bookTxt.getFeatureUrl().equals("")) {
                bookTxt.setFeature(txt2String(bookTxt.getFeatureUrl()));
            }
            if (bookTxt.getContentUrl() != null && !bookTxt.getContentUrl().equals("")) {
                bookTxt.setContent(txt2String(bookTxt.getContentUrl()));
            }
            if (bookTxt.getCatalogUrl() != null && !bookTxt.getCatalogUrl().equals("")) {
                bookTxt.setCatalog(txt2String(bookTxt.getCatalogUrl()));
            }
            if (bookTxt.getRelinfoUrl() != null && !bookTxt.getRelinfoUrl().equals("")) {
                bookTxt.setRelinfo(txt2String(bookTxt.getRelinfoUrl()));
            }
            if (bookTxt.getAuthorinfoUrl() != null && !bookTxt.getAuthorinfoUrl().equals("")) {
                bookTxt.setAuthorinfo(txt2String(bookTxt.getAuthorinfoUrl()));
            }
            book.setBookTxt(bookTxt);
            //封装书籍类型
            SecondType secondType=new SecondType();
            secondType.setId(book.getTypeId());
            secondType=secondTypeDao.select(secondType,false,false,new PageBean(),false,null).get(0);
            secondType=secondTypeHaveFirst(secondType);
            book.setSecondType(secondType);
            return book;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


